package com.cloudkinto.common.utils;

import okhttp3.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * Author Administrator
 *
 * @Des
 * @Version
 * @Date 2020/4/16
 */
public class OkHttpUtils {
    public static String okHttpRequest(String requestUrl, String requestMethod, String outputStr, String authorization) {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 1081);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).proxy(proxy).retryOnConnectionFailure(false);
        String url = requestUrl;
        Request request = new Request.Builder().addHeader("Authorization", authorization).addHeader("Content-type", "application/json")
//                .addHeader("Host", "api.rms.rakuten.co.jp")
//                .addHeader("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
//                .addHeader("User-Agent", Version.userAgent())
//                .addHeader("companyId", "1")
//                .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNTY5ODk4ODQxfQ.nQdV49X8jKLW3qHQYsXBC8qVrSyfYLBPiF1qHGVQsxk")
                .url(requestUrl).post(RequestBody.create(MediaType.get("application/json"), outputStr)).build();
        System.out.println(outputStr);
        Response response = null;
        String body = "";
        try {
            response = builder.build().newCall(request).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    public static String okHttpRequest(String requestUrl, String requestMethod, String outputStr) {
        OkHttpClient.Builder builder = getUnsafeOkHttpClient().newBuilder();
        builder.connectTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).retryOnConnectionFailure(false);
        String url = requestUrl;
        Request request = new Request.Builder().addHeader("Content-type", "application/json")
//                .addHeader("Host", "api.rms.rakuten.co.jp")
//                .addHeader("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
//                .addHeader("User-Agent", Version.userAgent())
//                .addHeader("companyId", "1")
//                .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNTY5ODk4ODQxfQ.nQdV49X8jKLW3qHQYsXBC8qVrSyfYLBPiF1qHGVQsxk")
                .url(requestUrl).post(RequestBody.create(MediaType.get("application/json"), outputStr)).build();
        System.out.println(outputStr);
        Response response = null;
        String body = "";
        try {
            response = builder.build().newCall(request).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    //okHttp3添加信任所有证书,支持https

    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[]{};
                }
            }};

            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, getX509TrustManager());

            builder.hostnameVerifier((hostname, session) -> true);
            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static X509TrustManager getX509TrustManager() {
        X509TrustManager x509TrustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

        };
        return x509TrustManager;
    }
}